package com.alibaba.csp.sentinel.dashboard.rule.apollo;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 扩展 DynamicRulePublisher
 */
@Component("flowRuleApolloPublisher")
public class FlowRuleApolloPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {

	private static FastDateFormat FASTDATEFORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss");
	
	@Autowired
	private Converter<List<FlowRuleEntity>, String> converter;
	
	@Override
	public void publish(String appName, List<FlowRuleEntity> rules) throws Exception {
		if(rules == null) {
			return ;
		}
		ApolloOpenApiClient client = ApolloConfigUtil.createApolloOpenApiClient(appName);

		if(client != null) {
			
			String dateFormat = FASTDATEFORMAT.format(new Date());
			
			//	具体的流控规则id
			String flowDataId = ApolloConfigUtil.getFlowDataId(appName);
			//	apollo的应用服务appId
			String appId = ApolloConfigUtil.getAppIdWithAppName(appName);
			
			OpenItemDTO dto = new OpenItemDTO();
			dto.setKey(flowDataId);
			dto.setValue(converter.convert(rules));
			dto.setComment("modify: " + dateFormat);
			dto.setDataChangeLastModifiedBy(ApolloConfig.USERID);
			dto.setDataChangeCreatedBy(ApolloConfig.USERID);
			
			// 1. 修改操作, 预发布
			client.createOrUpdateItem(appId, ApolloConfig.ENV, ApolloConfig.CLUSTERNAME, ApolloConfig.NAMESPACE, dto);
			
			// 2. 真正的进行发布
			NamespaceReleaseDTO releaseDTO = new NamespaceReleaseDTO();
			releaseDTO.setEmergencyPublish(true);
			releaseDTO.setReleaseComment("modify comment: " + dateFormat);
			releaseDTO.setReleaseTitle("发布新属性：" + dateFormat);
			releaseDTO.setReleasedBy(ApolloConfig.USERID);
			client.publishNamespace(appId, ApolloConfig.ENV, ApolloConfig.CLUSTERNAME, ApolloConfig.NAMESPACE, releaseDTO);
			
		} else {
			System.err.println("client is null, publish failed!");
		}
	}

	
	
	
	
	
	
	
	
	
}
